var ReasonMap = {0:"暂停"};
// 2.处理接收各种事件
// ------------------------ request event ------------------------------------------
function e_OnAgentNotReady(reason) {
    $('#readybtn').removeClass("invisable");
    $('#agent-state-btn').removeClass("btn-success");
    $('#agent-state-btn').addClass("btn-warning");
    stopClock();
    startClock();
    $('#callStatus').html(ReasonMap[reason]);
}

function e_OnAgentLoggedOn() {
    stopClock();
    startClock();
    stateChange(1);
	$('#callStatus').html("暂停")
}

function e_OnAgentReady() {
    $('#readybtn').addClass("invisable");
    $('#agent-state-btn').addClass("btn-success");
    $('#agent-state-btn').removeClass("btn-warning");
    $('#callStatus').html("空闲");
    stopClock();
    startClock();
}

function e_OnAgentLoggedOff() {
    stopClock();
    startClock();
    $('#callStatus').html("未连接");
   /* $('#callStatus').html("未登录");
    $('#stationnum').html("");   // 设置分机号
    $('#agentnum').html("未登录");     // 设置座席号
    $("#domainS").html("");
	$("#sname").html("");*/
	
	/*resetGlobalVars();
	resetReadyBtn();
	stateChange(0);
	*/

    window.location.reload();
}


function e_OnAgentWorkingAfterCall() {
    $('#callStatus').html("话后处理");
    //后处理标识
    phone.isAfterCall = 1;
    if(phone.readyOFF =="1"){
        //自动进线
        //通话中暂停跳过后处理，设置暂停
        if(phone.isPause){
            _setAgentStateS(phone.domain,phone.deviceId,phone.agtId, "1", "NotReady", "101", workMode);
        }else{
            //自动进线延迟
            setTimeout(function(){
                //正常挂断
                //延迟几秒、秒之内点未点击暂停
                if(!phone.isPause){
                    _setAgentStateS(phone.domain,phone.deviceId,phone.agtId, "0", "Ready", "101", workMode);
                }
            },phone.readyDelay);
        }
    }else{
        //手动进线
        _setAgentStateS(phone.domain,phone.deviceId,phone.agtId, "1", "NotReady", "101", workMode);
    }
}

// 振铃
function e_OnDeliveredEvt(evt_info) {
    stopClock();
    startClock();
    var caller = evt_info.callingDevice;          // 主叫
    var callee = evt_info.calledDevice;           // 被叫
    var alertingDevice = evt_info.alertingDevice; // 被叫
    var callid = evt_info.callId;
    var callType = 1;
    var wayBillNo = "";
    phone.lastCall.callId = evt_info.callId;
    phone.lastCall.ani = evt_info.callingDevice;
    phone.lastCall.dnis = evt_info.calledDevice;
    phone.isCallIn = true;//2018-05-16
    writeLog("振铃事件alertingDevice " + alertingDevice);
    try {
        //弹屏参数
        phone.lastCall.ivrList = evt_info["uui"].split("|");
        callType = getCallType(phone.lastCall.ivrList[5]);
        wayBillNo = phone.lastCall.ivrList[6] == "null"?"":phone.lastCall.ivrList[6];
    }catch (e) {
        console.error(e);
    }

    if(call1 == null ||  callid == call1.callid){
        //振铃记时开始
        if(phone.lastCall.offHookTime == "") {
            var objDate = new Date();
            phone.lastCall.offHookTime = $.date.dateFormat(objDate, 'yyyy-MM-dd hh:mm:ss');
            if (phone.tmrDur != "") {
                clearInterval(phone.tmrDur);
            }
            phone.tmrDur = setInterval(function () {
                var objDate = new Date();
                var nSecond = $.date.dateDiff('s', $.date.stringToDate(phone.lastCall.offHookTime), objDate);
                phone.talkTime = nSecond;
                try {
                    setAgtCountInfo(phone.deviceId, phone.workTime, phone.groupId, $.date.dateFormat(phone.talkTime, 'hh:mm:ss'), phone.callCnt + "/" + phone.dialOutCnt, $.date.dateFormat(phone.totalTalkTime, 'hh:mm:ss'));
                    //parent.setAgtCountInfo(SdAgent.agtId,phone.workTime,phone.groupId,$.date.dateFormat(phone.talkTime,'hh:mm:ss'),phone.callCnt+"/"+phone.dialOutCnt,$.date.dateFormat(phone.totalTalkTime,'hh:mm:ss'));
                } catch (e) {
                }
            }, 1000);
        }
		if(alertingDevice == null || alertingDevice == ""){
            writeLog("振铃事件alertingDevice " + alertingDevice)
			stateChange(2);
		}else if(alertingDevice == phone.deviceId){
            // 被叫和分机相同为呼入
            phone.callCnt+=1;
            $("#Bar_CallInNUm").html(phone.lastCall.ani);//来电号码
            stateChange(5);
            window.parent.callScreenPopUp(phone.lastCall.callId ,callType, wayBillNo, phone.lastCall.ani,null,null,null);
        }else{
            // 座席呼出
            $('#Bar_CallInNUm').html(phone.lastCall.dnis);
            //外呼
            phone.dialOutCnt+=1;
            stateChange(2);
        }
        call1 = new CallObject();
        call1.callid = callid;
        call1.ani = caller;
        call1.dnis = callee;
		call1.state = 1;
        currentCallId = callid;
        writeLog("[ add calll-1 ] " + JSON.stringify(call1)) ;
    }else{
        stateChange(2);
        call2 = new CallObject();
        call2.callid = callid;
        call2.ani = caller;
        call2.dnis = callee;
		call2.state = 1;
		currentCallId = callid;
        writeLog("[ add calll-2 ]" + JSON.stringify(call2)) ;
    }

    $('#callStatus').html("振铃");
}

// 接通
function e_OnEstablishedEvt(evt_info) {
    writeLog('****通话成功from:'+evt_info.callingDevice+"to:"+evt_info.calledDevice);
    stopClock();
    startClock();
    var callid =  evt_info.callId;
	
	conferenceTag = false;
	
	if(call1 == null){
		call1 = new CallObject();
        call1.callid = callid;
        call1.ani = evt_info.callingDevice;
        call1.dnis = evt_info.calledDevice;
		call1.state = 2;
        currentCallId = evt_info.callId;
	}
	
    if(call1 != null){
        if(call1.callid == callid){
            stateChange(3);
			call1.state = 2;
        }else if(call2 != null && call2.callid == callid){
			stateChange(6);
			call2.state = 2;
		}
    }else{
		if(call2 != null && call2.callid == callid){
			stateChange(6);
			call2.state = 2;
		}
	}

    $('#callStatus').html("已接通");
    $('#incalltime').html("");

}
// 挂断
function e_OnConnectionClearedEvt(evt_info) {
    stopClock();
    startClock();
    var callid =  evt_info.callId;
	var tag = 0;
	
    if(call1 != null){
        if(call1.callid == callid && evt_info.releasingDevice == phone.deviceId){
            call1 = null;
            writeLog("[ hangupCall remove call-l] callid " + callid) ;
            stateChange(1);
			tag = 1;
			conferenceTag = false;
        }
    }
	
	if(call2 != null){
        if(call2.callid == callid && evt_info.releasingDevice == phone.deviceId){
            writeLog("[ hangupCall remove call-2] callid " + callid) ;
            $('#callStatus').html("已接通");
            call2 = null;
			if(tag == 1){
				stateChange(1);
			}else{
				if(call1 != null){
					if(call1.state == 2){
						stateChange(3);
					}else if(call1.state == 3){
						stateChange(4);
					}
				}else{
					stateChange(1);
				}
				
			}
        }else if(call1 == null){
			if(call2.state == 3){
				stateChange(4);
			}else{
				stateChange(3);
			}
		}
    }
	
	if(call1 == null && call2 != null){
		call1 = call2;
		call2 = null;
	}
	if(call1 == null && call2 == null){
		currentCallId = "";
	}
    //$('#callStatus').html("已挂断");
    phone.clearCall();
    window.parent.qxsucc();
}

//保持
function e_OnHeldEvt(evt_info) {
    phone.isHoldCall = true;
    stopClock();
    startClock();
    var callid =  evt_info.callId;
	var holdDevice = evt_info.holdingDevice;
	
    if(call1 != null && call2 == null && phone.deviceId == holdDevice){
		call1.state = 3;
		writeLog("[ hold call-l] callid " + callid) ;
		stateChange(4);
    }
	if(call1 != null && call2 != null && phone.deviceId == holdDevice){
        if(call2.callid == callid){
			call2.state = 3;
            writeLog("[ hold call-2] callid " + callid);
        }
		if(call1.callid == callid && phone.deviceId == holdDevice){
			call1.state = 3;
            writeLog("[ hold call-1] callid " + callid);
        }
		stateChange(6);
    }
	if(call2 != null && call1 == null && phone.deviceId == holdDevice){
		if(call2.callid == callid ){
			call2.state = 3;
			writeLog("[ hold call-2] callid " + callid);
			stateChange(4);
		}
	}
    $('#callStatus').html("保持");
    $('#incalltime').html("");
}

// 取回
function e_OnRetrievedEvt(evt_info) {
    phone.isHoldCall = false;
    stopClock();
    startClock();
    var callid =  evt_info.callId;
	var retrievingDevice = evt_info.retrievingDevice;
    if(call1 != null && call2 == null && retrievingDevice == phone.deviceId){
		call1.state = 2;
		writeLog("[ retrieve call-l] callid " + callid) ;
		stateChange(3);
    }
	if(call1 != null && call2 != null && retrievingDevice == $("#stationnum").text().trim()){
		if(call1.callid == callid){
			call1.state = 2;
            writeLog("[ retrieve call-l] callid " + callid) ;
            stateChange(6);
        }else if(call2.callid == callid){
			call2.state = 2;
			writeLog("[ retrieve call-2] callid " + callid) ;
			stateChange(6);
		}
	}
	if(call2 != null && call1 == null && retrievingDevice == phone.deviceId){
		if(call2.callid == callid){
			call2.state = 2;
            writeLog("[ retrieve call-2] callid " + callid) ;
            stateChange(3);
        }
	}
	
	if(conferenceTag){
		stateChange(7);
		$('#callStatus').html("会议中");
		$('#incalltime').html("");
	}else{
		$('#callStatus').html("已接通");
		$('#incalltime').html("");
	}
}

// 转接
function e_OnTransferedEvt(evt_info) {
    stopClock();
    startClock();
    var callid =  evt_info.newCall;
    var transferredToDevice = evt_info.transferredToDevice;
	var secondaryOldCall = evt_info.secondaryOldCall;
	var primaryOldCall = evt_info.primaryOldCall;
	var transferringDevice = evt_info.transferringDevice;
	
	if(transferringDevice == $("#stationnum").text().trim()){ //转移方
		writeLog("transfer success");
		call1 = null;
		call2 = null;
		stateChange(1);
		$('#callStatus').html("已转移");
		$('#incalltime').html("");
	}else if(transferredToDevice == phone.deviceId){//目标分机
        if(call1 != null){
			writeLog("transfer [ 目标分机 ]");
			if(call2 != null){
				call1.callid = callid;
				writeLog("[ [warning] primary caller transfer his call to you! update call-1] callid " + callid);
			}else{
				call1.callid = callid;
				currentCallId = callid;
				writeLog("[ transfer to call-l] callid " + callid);
				stateChange(3);
			}
			$('#callStatus').html("已接通");
			$('#incalltime').html("");
        }
    }else if(call1 != null){// 被转移方
		writeLog("transfer [ 被转移方 ]");
		if(call1.callid == primaryOldCall){
			call1.callid = callid;
            currentCallId = callid;
            writeLog("[ transfer to call-l] callid " + callid);
            stateChange(3);
		} else if (call2 != null && call2.callid == primaryOldCall){
			call2.callid = callid;
            currentCallId = callid;
            writeLog("[ transfer to call-2] callid " + callid);
            stateChange(6);
		}
		$('#callStatus').html("已接通");
		$('#incalltime').html("");
	}else{
		stateChange(1);
	}
}

function e_OnConferencedEvt(evt_info) {
    stopClock();
    startClock();
	conferenceTag = true;
    var callid =  evt_info.newCall;
    call1.callid = callid;
	call1.state = 2;
	writeLog("[ transfer to call-l] callid " + callid);
    stateChange(7);
    $('#callStatus').html("会议中");
    $('#incalltime').html("");
}

function e_OnQueueNumChangeEvent(evt) {
    var skillId = evt.skill;
    var queueNum = evt.count;
    queueMap[skillId] = queueNum;

    var totalQueueNum = 0;
    for (let key in queueMap) {
        totalQueueNum += queueMap[key];
    }
    $("#queueInfo").html(totalQueueNum+"人");
    console.log(totalQueueNum);
}

/**
 * 弹屏区分快递，快运
 * @param typeStr
 * @returns 1:快递,2,快运
 */
function getCallType(typeStr){
    if(null == typeStr||typeStr == "undefined")return 1;
    if(typeStr == "KD=1"){
        return 1;
    }else if(typeStr == "KD=2")return 2;
}
